import { login, getInfo } from '@/api/user';
import {
  ACCESS_TOKEN,
  REFRESH_TOKEN,
  setToken,
  removeToken,
  setRouterItem,
  removeRouterItem,
  getRefreshToken,
  getAccessToken,
} from '@/utils/storage';
import { resetRouter } from '@/router';
// import { md5 } from '@/utils/validate';

const state = {
  access_token: getAccessToken(),
  refresh_token: getAccessToken(),
  name: '',
  avatar: '',
  // roles: [],
  user_id: '',
  router_id: [],
  cachedViews: ['news_create', 'news_edit'],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.access_token = token.accessToken;
    state.refreshToken = token.refreshToken;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  // SET_ROLES: (state, roles) => {
  //   state.roles = roles
  // },
  SET_ROUTER_ID: (state, routerId) => {
    state.router_id = routerId;
  },
  SET_USER_ID: (state, userid) => {
    state.user_id = userid;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      // md5(password)
      login({ username: username.trim(), password })
        .then((response) => {
          const { accessToken, refreshToken } = response;
          // setRouterItem(views);
          commit('SET_TOKEN', { accessToken, refreshToken });
          commit('SET_NAME', username);
          // commit('SET_ROUTER_ID', ['permision']);
          setToken(ACCESS_TOKEN, accessToken);
          setToken(REFRESH_TOKEN, refreshToken);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.name || 'admin')
        .then(async (response) => {
          // const {username, userid, views, exp, roles, name, avatar} = data;

          if (!response) {
            reject('no response');
            throw new Error('get user Info no response');
          }
          const { username, userid, views } = response;
          // 考虑 exp 设置到Cookie中 方便同步过期时间

          // roles must be a non-empty array
          if (!views || views.length <= 0) {
            reject('getInfo: views must be a non-null array!');
          }
          // commit('SET_ROLES', roles);
          commit('SET_NAME', username);
          commit('SET_USER_ID', userid);
          commit(
            'SET_AVATAR',
            'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          );
          commit('SET_ROUTER_ID', views);
          setRouterItem(views);
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('SET_TOKEN', { accessToken: '', refreshToken: '' });
        commit('SET_ROUTER_ID', []);
        removeToken(ACCESS_TOKEN);
        resetRouter();
        removeRouterItem();
        resolve();
      }, 0);
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resetRouter()
      //   removeRouterItem()
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '');
      // commit('SET_ROLES', [])
      removeToken(ACCESS_TOKEN);
      resolve();
    });
  },

  // dynamically modify permissions
  /* changeRoles({commit, dispatch}, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {roles} = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {root: true})

      resolve()
    })
  } */
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
